//
//  TouchID.swift
//  EWEMDT3
//
//  Created by 来 on 2019/11/21.
//  Copyright © 2019 laiguofeng. All rights reserved.
//

import Foundation

import LocalAuthentication

public typealias TouchIDEvaluateCompletionClosure = (_ success: Bool, _ error: Error?) -> Swift.Void

public class TouchID {
    
    static let kDefaultLAPolicy: LAPolicy = .deviceOwnerAuthenticationWithBiometrics
    
    static var isEnabled: Bool {
        return isTouchIDEnabled().isEnabled
    }
    
    class func isTouchIDEnabled(policy: LAPolicy = TouchID.kDefaultLAPolicy) -> (isEnabled: Bool, error: NSError?) {
        let context = LAContext()
        var error: NSError?
        let isEnabled = context.canEvaluatePolicy(policy, error: &error)
        if error != nil && error!.code == -6 {
            return (isEnabled, error)
        } else {
            return (true, error)
        }
    }
    
    class func evaluate(_ policy: LAPolicy = TouchID.kDefaultLAPolicy,
                             reason: String,
                             fallbackTitle: String? = nil,
                             cancelTitle: String? = "取消",
                             completion: @escaping TouchIDEvaluateCompletionClosure) {
        if !isTouchIDEnabled(policy: policy).isEnabled {
            completion(false, LAError.touchIDNotAvailable as? Error)
            return
        }
        
        let context = LAContext()
        context.localizedFallbackTitle = fallbackTitle
        if #available(iOS 10.0, *) {
            context.localizedCancelTitle = cancelTitle
        }
        
        context.evaluatePolicy(policy, localizedReason: reason) { (success, error) in
            completion(success, error)
            
        }
    }
    
    @available(iOS 9.0, *)
    class func evaluate(_ accessControl: SecAccessControl,
                             operation: LAAccessControlOperation,
                             reason: String,
                             fallbackTitle: String? = nil,
                             cancelTitle: String? = nil,
                             completion: @escaping TouchIDEvaluateCompletionClosure) {
        let context = LAContext()
        context.localizedFallbackTitle = fallbackTitle
        context.evaluateAccessControl(accessControl, operation: operation, localizedReason: reason, reply: completion)
    }
    
}
